package com.twu.biblioteca;

import com.twu.biblioteca.command.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: twer
 * Date: 5/22/13
 * Time: 12:07 AM
 * To change this template use File | Settings | File Templates.
 */
public class CommandCenter {
    private Map<String, Command> commandMap;
    public CommandCenter(){
        commandMap = null;
    }

    private void initCommandMap(){
        commandMap = new HashMap<String, Command>();
        commandMap.put("1", new ViewBooksCommand());
        commandMap.put("2", new BadCommand());
        commandMap.put("3", new CheckMembershipCommand());
        commandMap.put("4", new ViewMoviesCommand());
        commandMap.put("5", new LoginCommand());
    }
    public Command getCommand(String code) {
        if (commandMap == null){
            useUnloginMenu();
        }
        return findCommand(code);
    }

    private Command findCommand(String code){
        Command command = commandMap.get(code);
        if (command == null){
            return new BadCommand();
        }
        return command;
    }

    public void useUnloginMenu(){
        if (commandMap != null){
            commandMap.clear();
        }
        commandMap = createUnloginMenu();
    }

    public void useLoginMenu(){
        if (commandMap != null){
            commandMap.clear();
        }
        commandMap = createLoginMenu();
    }

    private Map<String, Command> createUnloginMenu(){
        Map<String, Command> commandMap = new HashMap<String, Command>();
        commandMap.put("1", new ViewBooksCommand());
        commandMap.put("2", new ViewMoviesCommand());
        commandMap.put("3", new CheckMembershipCommand());
        commandMap.put("4", new LoginCommand());
        commandMap.put("m", new ViewMenuCommand());
        commandMap.put("q", new QuitCommand());
        return commandMap;
    }

    private Map<String, Command> createLoginMenu(){
        Map<String, Command> commandMap = new HashMap<String, Command>();
        commandMap.put("1", new ViewBooksCommand());
        commandMap.put("2", new ViewMoviesCommand());
        commandMap.put("3", new CheckMembershipCommand());
        commandMap.put("4", new LoginCommand());
        commandMap.put("m", new ViewMenuCommand());
        return commandMap;
    }

    public String menu() {
        if (commandMap == null){
            useUnloginMenu();
        }
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Command> entry : commandMap.entrySet()){
            builder.append(entry.getKey());
            builder.append(".");
            builder.append(entry.getValue().title());
            builder.append("\n");
        }
        return builder.toString();
    }
}
